package top.yonyong.mynacos.configcenter.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import top.yonyong.mynacos.configcenter.config.inteceptor.MyInterceptor;

/**
 * @Describtion common view router
 * @Author yonyong
 * @Date 2020/7/6 9:19
 * @Version 1.0.0
 **/
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {

    /**
     * add request view mapping config
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addStatusController("/404", HttpStatus.NOT_FOUND);
        registry.addStatusController("/error", HttpStatus.INTERNAL_SERVER_ERROR);
        registry.addViewController("/index").setViewName("/index");
        registry.addViewController("/404").setViewName("/404");
        registry.addViewController("/error").setViewName("/error");
    }

    /**
     * cors configuration
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                //浏览器允许所有的域访问 / 注意 * 不能满足带有cookie的访问,Origin 必须是全匹配
                .allowedOrigins("**")
                // 允许带cookie访问
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .exposedHeaders("token")
                .maxAge(3600);
    }

    /**
     *  add interceptor
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
    }
}
